<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="主要内容 内容 介绍、安装及常用命令 webpack基本配置说明 webpack配置 优化 原理 手写webpack插件 手写loader 总结  介绍、安装及常用命令什么是webpack自从出现模块化以后，大家可以将原本一坨代码分离到个个模块中，但是由此引发了一个问题。每个 JS 文件都需要从服务器去拿，由此会导致加载速度变慢。Webpack 最主要的目的就是为了解决这个问题，将所有小文件打包成">
<meta property="og:type" content="article">
<meta property="og:title" content="webpack学习记录">
<meta property="og:url" content="http://blog.xiaowuzi.info/2018/12/08/webpack学习记录/index.html">
<meta property="og:site_name" content="小武子博客">
<meta property="og:description" content="主要内容 内容 介绍、安装及常用命令 webpack基本配置说明 webpack配置 优化 原理 手写webpack插件 手写loader 总结  介绍、安装及常用命令什么是webpack自从出现模块化以后，大家可以将原本一坨代码分离到个个模块中，但是由此引发了一个问题。每个 JS 文件都需要从服务器去拿，由此会导致加载速度变慢。Webpack 最主要的目的就是为了解决这个问题，将所有小文件打包成">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2017/9/15/92a95decddcecb9e25304f3b6a9dfb9c?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="http://blog.xiaowuzi.info/images/webpack/01.jpg">
<meta property="og:updated_time" content="2018-12-09T07:07:50.908Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="webpack学习记录">
<meta name="twitter:description" content="主要内容 内容 介绍、安装及常用命令 webpack基本配置说明 webpack配置 优化 原理 手写webpack插件 手写loader 总结  介绍、安装及常用命令什么是webpack自从出现模块化以后，大家可以将原本一坨代码分离到个个模块中，但是由此引发了一个问题。每个 JS 文件都需要从服务器去拿，由此会导致加载速度变慢。Webpack 最主要的目的就是为了解决这个问题，将所有小文件打包成">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2017/9/15/92a95decddcecb9e25304f3b6a9dfb9c?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiaowuzi.info/2018/12/08/webpack学习记录/">





  <title>webpack学习记录 | 小武子博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">小武子博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiaowuzi.info/2018/12/08/webpack学习记录/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小武子博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">webpack学习记录</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-08T13:30:11+08:00">
                2018-12-08
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/工具/" itemprop="url" rel="index">
                    <span itemprop="name">工具</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>主要内容</p>
<h3 id="内容"><a href="#内容" class="headerlink" title="内容"></a>内容</h3><ol>
<li>介绍、安装及常用命令</li>
<li>webpack基本配置说明</li>
<li>webpack配置</li>
<li>优化</li>
<li>原理</li>
<li>手写webpack插件</li>
<li>手写loader</li>
<li>总结</li>
</ol>
<h3 id="介绍、安装及常用命令"><a href="#介绍、安装及常用命令" class="headerlink" title="介绍、安装及常用命令"></a>介绍、安装及常用命令</h3><h4 id="什么是webpack"><a href="#什么是webpack" class="headerlink" title="什么是webpack"></a>什么是webpack</h4><p>自从出现模块化以后，大家可以将原本一坨代码分离到个个模块中，但是由此引发了一个问题。每个 JS 文件都需要从服务器去拿，由此会导致加载速度变慢。Webpack 最主要的目的就是为了解决这个问题，将所有小文件打包成一个或多个大文件，官网的图片很好的诠释了这个事情，除此之外，Webpack 也是一个能让你使用各种前端新技术的工具。</p>
<p><img src="https://user-gold-cdn.xitu.io/2017/9/15/92a95decddcecb9e25304f3b6a9dfb9c?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="image"><br><a id="more"></a><br>webpack一共经历了4个版本，分别是1、2、3、4，最新版本是4，以下案例是基于4实践的</p>
<h4 id="webpack特点"><a href="#webpack特点" class="headerlink" title="webpack特点"></a>webpack特点</h4><ol>
<li>专注于处理模块化的项目，能做到开箱即用、一步到位；</li>
<li>可通过Plugin扩展，完整好用又不失灵活；</li>
<li>使用场景不局限于web开发；</li>
<li>社区庞大活跃，经常引入紧跟时代发展的新特性，能为大多数场景找到自己有的开源扩展；</li>
<li>良好的开发体验；</li>
</ol>
<p>——自来《深入浅出webpack》</p>
<h4 id="webpack安装"><a href="#webpack安装" class="headerlink" title="webpack安装"></a>webpack安装</h4><p>全局安装webpack</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install -g webpack</span><br></pre></td></tr></table></figure>
<p>局部安装webpack</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install --save-dev webpack</span><br></pre></td></tr></table></figure>
<h4 id="常用命令"><a href="#常用命令" class="headerlink" title="常用命令"></a>常用命令</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">webpack -p 执行一次生成环境的编译（压缩）</span><br><span class="line">webpack --watch 在开发时持续监控增量编译（很快）</span><br><span class="line">webpack -d 让他生成SourceMaps</span><br><span class="line">webpack --progress 显示编译进度</span><br><span class="line">webpack --colors 显示静态资源的颜色</span><br><span class="line">webpack --sort-modules-by, --sort-chunks-by, --sort-assets-by 将modules/chunks/assets进行列表排序</span><br><span class="line">webpack --display-chunks 展示编译后的分块</span><br><span class="line">webpack --display-reasons 显示更多引用模块原因</span><br><span class="line">webapck --display-error-details 显示更多报错信息</span><br></pre></td></tr></table></figure>
<h3 id="最简单配置"><a href="#最简单配置" class="headerlink" title="最简单配置"></a>最简单配置</h3><h4 id="webpack相关参数介绍"><a href="#webpack相关参数介绍" class="headerlink" title="webpack相关参数介绍"></a>webpack相关参数介绍</h4><h5 id="1-entry"><a href="#1-entry" class="headerlink" title="1. entry"></a>1. entry</h5><p>配置模块的入口</p>
<p>Entry参数说明，类型可以是以下三种中的一种或者相互组合</p>
<table>
<thead>
<tr>
<th>类型</th>
<th>例子</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>string</td>
<td>‘./app/entry’</td>
<td>入口模块的文件路径，可以相对路径</td>
</tr>
<tr>
<td>array</td>
<td>[‘./app/entry1’,’./app/entry2’]</td>
<td>入口模块的文件路径，可以是相对路径</td>
</tr>
<tr>
<td>object</td>
<td>{a:[‘./app/entry-a’],b:[‘./app/entry-b1’,’./app/entry-b2’]}</td>
<td>配置多个入口，每个入口生成一个chunk</td>
</tr>
</tbody>
</table>
<h5 id="2-output"><a href="#2-output" class="headerlink" title="2. output"></a>2. output</h5><p>配置如何输出最终想要的代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">output是一个object,里面包含一系列配置项</span><br><span class="line"></span><br><span class="line">output.filename:&apos;[name].js&apos;  //输出文件的名称</span><br><span class="line">也可以使用hash、chunkhash、contenthash来命名，关于hash、chunkhash、contenthash区别可以参考https://www.cnblogs.com/tugenhua0707/p/9615822.html#_labe1_2</span><br><span class="line"></span><br><span class="line">output.chunkFilename://chunkFilename 和上面的 filename 非常类似，但 chunkFilename 只用于指定在运行过程中生成的 Chunk 在输出时的文件名称，vue按需加载就可以使用这个参数</span><br><span class="line"></span><br><span class="line">output.path：path .resolve( dirname, ’ dist [hash]’) //path 配置输出文件存放在本地的目录</span><br><span class="line">output.publicPath:&apos;https://cdn.example.com/assets/&apos; //配置发布到线上资源的 URL 前缀</span><br><span class="line">output.libraryTarget://配置以何种方式导出库，可选值var、commonjs、commonjs2、this、window、global</span><br><span class="line">output.library://配置导出库的名称。</span><br><span class="line">output.libraryExport: 配置要导出的模块中哪些子模块需要被导出</span><br></pre></td></tr></table></figure></p>
<h5 id="3-module"><a href="#3-module" class="headerlink" title="3. module"></a>3. module</h5><p>3.1 rules </p>
<p>rules 配置模块的读取和解析规则，通常用来配置 Loader。大致可以通过以下方式来完成</p>
<p>条件匹配:通过 test、 include、 exclude 三个配置项来选中 Loader 要应用 规则的文件。</p>
<p>应用规则：对选中的文件通过 use 配置项来应用 Loader，可以只应用一个 Loader或者按照从后往前的顺序应用一组 Loader，同时可以分别向 Loader传入参数。</p>
<p>重置顺序:一组 Loader 的执行顺序默认是从右到左执行的，通过 enforce 选项可以将其中 一个 Loader 的执行顺序放到最前或者最后 。</p>
<p>具体方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">module:&#123;</span><br><span class="line">    rules:[</span><br><span class="line">        &#123;</span><br><span class="line">            //命中 JavaScript 文件</span><br><span class="line">            test: /\.js$/，</span><br><span class="line">            //用 babel-loader 转换 JavaScript 文件</span><br><span class="line">            //?cacheDirectory 表示传给 babel-loader 的参数，用于缓存 babel 的编译结果，</span><br><span class="line">            use : [’ babel-loader?cacheDirectory ’],</span><br><span class="line">            //只命中 src 目录里的 JavaScript 文件，加快 Webpack 的搜索速度 </span><br><span class="line">            include: path.resolve( dirname, ’ src ’)</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">            //命中scss文件</span><br><span class="line">            test:/\.scss$/,</span><br><span class="line">            //使用一组loader去处理scss文件</span><br><span class="line">            //处理顺序为从后到前，即先交给 sass-loader处理，再将结果交给 css-loader,最后交给 style-loader</span><br><span class="line">            use:[&apos;style-loader&apos;,&apos;css-loader&apos;,&apos;sass-loader&apos;],</span><br><span class="line">            //排除node_modules目录下的文件</span><br><span class="line">            exclude: path.resolve( dirname, ’ node modules ’)</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">            //对非文件采用file-loader加载</span><br><span class="line">            test:/\.(gif|png|jpe?g|eot|woff|ttf|svg|pdf)$/,</span><br><span class="line">            use:[&apos;file-loader&apos;]</span><br><span class="line">        &#125;</span><br><span class="line">    ]</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>3.2 noParse</p>
<p>配置项可以让Webpack忽略对部分没采用模块化的文件的递归解析和处理，这样做的好处能提高构建性能。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">    //使用正则表达式</span><br><span class="line">noParse: /jquerylchartjs/</span><br></pre></td></tr></table></figure>
<p>注意，被忽略的文件里不应该包含 import、 require、 define 等模块化 语句，不 然会导致在构建出的代码中包含无法在浏览器环境下执行的模块化语句 。</p>
<p>3.3. parse</p>
<p>parser 属性可以更细粒度地配置 哪些模块语法被解析、哪些不被解析。同 noParse 配置项的区别在于， parser 可以精确到 语法层 面，而 noParse 只能控制哪些文件不被解析。</p>
<p>parser 的使用方法如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">module: &#123; </span><br><span class="line">    rules : [</span><br><span class="line">        &#123;</span><br><span class="line">        test: /\.js♀/，</span><br><span class="line">        use: [ ’ babel-loader ’],</span><br><span class="line">        parser: &#123;</span><br><span class="line">            amd: false， //禁用AMD</span><br><span class="line">            commonjs : false , //禁用 CommonJS</span><br><span class="line">            system : false, //禁用 SystemJS</span><br><span class="line">            harmony: false， //禁用 ES6 import/export</span><br><span class="line">            requireinclude:false,   //禁用require.include</span><br><span class="line">            requireEnsure: false,   //禁用require.ensure</span><br><span class="line">            requireContext:false,   //禁用require.context</span><br><span class="line">            browserify: false, //禁用 browserify requireJs : false, //禁用 requirejs:false</span><br><span class="line">            requireJs : false, //禁用 requirejs</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="4-resolve"><a href="#4-resolve" class="headerlink" title="4. resolve"></a>4. resolve</h5><p>配置寻找模块的规则</p>
<p>4.1. alias<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">配置项通过别名来将原导入路径映射成一个新的导入路径</span><br><span class="line"></span><br><span class="line">resolve:&#123;</span><br><span class="line">    alias:&#123;</span><br><span class="line">        components:&apos;./src/components/&apos;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>4.2. mainFields</p>
<p>会根据 mainFields 的配 置去决定 优先采用哪份代码，</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mainFields : [’jsnext:main’,’browser’,’main’]</span><br></pre></td></tr></table></figure>
<p>4.3. extensions</p>
<p>Webpack 会自动带上后缀后去尝试访问文件是否存在。 resolve.extensions 用于配置在尝试过程中用到的后缀列表</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">extensions:[’.ts’,’.j5 ’,’.json’]</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>plugins</li>
</ol>
<p>配置扩展插件</p>
<p>plugins配置项接收一个数组，数组里的每一项都是一个要使用 的 Plugin 的实例， Plugin 需要的参数通过构造函数传入,mini-css-extract-plugin、clean-webpack-plugin、DllReferencePlugin、html-webpack-plugin、happyPack、webpack-parallel-uglify-plugin</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">const ClearWebpackPlugin = require(&apos;clean-webpack-plugin&apos;);</span><br><span class="line"></span><br><span class="line">module.exports=[</span><br><span class="line">    plugins:[</span><br><span class="line">        new ClearWebpackPlugin([&apos;dist&apos;])</span><br><span class="line">    ]</span><br><span class="line">];</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>DevServer</li>
</ol>
<p>hot,开启模块热替换功能后，将在不刷新整个页面的情况下通过用新模块替换老模块来做到实时预览</p>
<p>inline,依赖一个注入页面里的代理客户端，去接收来自 DevServer的 命令并负责刷新网页的工作。</p>
<p>contentBase,配置 DevServerHTTP服务器的文件根目录</p>
<h3 id="webpack配置"><a href="#webpack配置" class="headerlink" title="webpack配置"></a>webpack配置</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br></pre></td><td class="code"><pre><span class="line">const path = require(&apos;path&apos;);</span><br><span class="line">const webpack = require(&apos;webpack&apos;);</span><br><span class="line">const HtmlWebpackPlugin = require(&apos;html-webpack-plugin&apos;);</span><br><span class="line">const MiniCssExtractPlugin = require(&quot;mini-css-extract-plugin&quot;);</span><br><span class="line">const ClearWebpackPlugin = require(&apos;clean-webpack-plugin&apos;);</span><br><span class="line">const DllReferencePlugin = require(&apos;webpack/lib/DllReferencePlugin&apos;);</span><br><span class="line">const ParallelUglifyPlugin = require(&apos;webpack-parallel-uglify-plugin&apos;);</span><br><span class="line">const HappyPack = require(&apos;happypack&apos;);</span><br><span class="line">module.exports = &#123;</span><br><span class="line">    entry: &apos;./app/index/app.js&apos;, //支持多个参数，string|array|object</span><br><span class="line">    output: &#123;</span><br><span class="line">        filename: &apos; [name].js&apos;, //输出文件名称</span><br><span class="line">        path: path.resolve(__dirname, &apos;./dist&apos;), //输出文件的目标路径</span><br><span class="line">        publicPath: &apos;/&apos; //构建文件的输出目录</span><br><span class="line">    &#125;,</span><br><span class="line">    devServer: &#123; //DevServer相关的配置</span><br><span class="line">        contentBase: path.join(__dirname, &apos;dist&apos;),</span><br><span class="line">        compress: true, //压缩</span><br><span class="line">        port: 8888, //端口号</span><br><span class="line">        open: true, //第一次打开浏览器</span><br><span class="line">        hot: true, //是否监听</span><br><span class="line">        publicPath: &quot;/&quot; //访问的目录</span><br><span class="line">    &#125;,</span><br><span class="line">    module: &#123;</span><br><span class="line">        rules: [&#123;</span><br><span class="line">                test: /\.js$/,</span><br><span class="line">                use: [&apos; babel-loader&apos;],</span><br><span class="line">                parser: &#123;</span><br><span class="line">                    amd: true, //禁用AMD</span><br><span class="line">                    commonjs: true, //禁用 CommonJS</span><br><span class="line">                    system: false, //禁用 SystemJS</span><br><span class="line">                    harmony: true, //禁用 ES6 import/export</span><br><span class="line">                    requireinclude: false, //禁用require.include</span><br><span class="line">                    requireEnsure: false, //禁用require.ensure</span><br><span class="line">                    requireContext: false, //禁用require.context</span><br><span class="line">                    browserify: false, //禁用 browserify requireJs : false, //禁用 requirejs:false</span><br><span class="line">                    requireJs: false, //禁用 requirejs</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;,</span><br><span class="line">            &#123;</span><br><span class="line">                // 用正则去匹配要用该 loader 转换的 CSS 文件</span><br><span class="line">                test: /\.css$/,</span><br><span class="line">                use: [&#123;</span><br><span class="line">                    loader: MiniCssExtractPlugin.loader,</span><br><span class="line">                &#125;, &#123;</span><br><span class="line">                    loader: path.resolve(&apos;./loaders.js&apos;),</span><br><span class="line">                    options: &#123;</span><br><span class="line">                        test: 1</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;, &#123;</span><br><span class="line">                    loader: &apos;css-loader?minimize&apos;,</span><br><span class="line">                &#125;, &#123;</span><br><span class="line">                    loader: &apos;postcss-loader&apos;,</span><br><span class="line">                    options: &#123;</span><br><span class="line">                        ident: &apos;postcss&apos;,</span><br><span class="line">                        plugins: [</span><br><span class="line">                            require(&apos;postcss-cssnext&apos;)(),</span><br><span class="line">                            require(&apos;cssnano&apos;)(),</span><br><span class="line">                            require(&apos;postcss-sprites&apos;)()</span><br><span class="line">                        ]</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;],</span><br><span class="line">            &#125;, &#123;</span><br><span class="line">                //图片处理</span><br><span class="line">                test: /\.(png|svg|jpg|gif)$/,</span><br><span class="line">                use: [&#123;</span><br><span class="line">                    loader: &apos;url-loader&apos;,</span><br><span class="line">                    options: &#123;</span><br><span class="line">                        limit: 10000,</span><br><span class="line">                        name: &apos;[name].[ext]&apos;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;]</span><br><span class="line">            &#125;</span><br><span class="line">        ]</span><br><span class="line">    &#125;,</span><br><span class="line">    resolve: &#123;</span><br><span class="line">        modules: [</span><br><span class="line">            // 模块的查找目录</span><br><span class="line">            &quot;node_modules&quot;,</span><br><span class="line">            path.resolve(__dirname, &quot;app&quot;)</span><br><span class="line">        ],</span><br><span class="line">        extensions: [&apos;.js&apos;, &apos;.json&apos;, &apos;.vue&apos;, &apos;.css&apos;],</span><br><span class="line">        alias: &#123; //模块别名列表</span><br><span class="line">            &apos;module&apos;: &apos;new-module&apos;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    devtool: &apos;source-map&apos;, //sourcemap</span><br><span class="line">    plugins: [ //插件部分</span><br><span class="line">        new ClearWebpackPlugin([&apos;dist&apos;]),</span><br><span class="line">        new MiniCssExtractPlugin(&#123;</span><br><span class="line">            // Options similar to the same options in webpackOptions.output</span><br><span class="line">            // both options are optional</span><br><span class="line">            filename: `[name]_[contenthash:8].css`,</span><br><span class="line">            chunkFilename: &apos;[name]_[contenthash:8].css&apos;</span><br><span class="line">        &#125;),</span><br><span class="line">        // 告诉webpack使用了哪些第三方库代码</span><br><span class="line">        new DllReferencePlugin(&#123;</span><br><span class="line">            // jquery 映射到json文件上去</span><br><span class="line">            manifest: require(&apos;./dill/jquery.manifest.json&apos;)</span><br><span class="line">        &#125;),</span><br><span class="line">        new ParallelUglifyPlugin(&#123;</span><br><span class="line">            // 传递给 UglifyJS的参数如下：</span><br><span class="line">            uglifyJS: &#123;</span><br><span class="line">                output: &#123;</span><br><span class="line">                    /*</span><br><span class="line">                     是否输出可读性较强的代码，即会保留空格和制表符，默认为输出，为了达到更好的压缩效果，</span><br><span class="line">                     可以设置为false</span><br><span class="line">                    */</span><br><span class="line">                    beautify: false,</span><br><span class="line">                    /*</span><br><span class="line">                     是否保留代码中的注释，默认为保留，为了达到更好的压缩效果，可以设置为false</span><br><span class="line">                    */</span><br><span class="line">                    comments: false</span><br><span class="line">                &#125;,</span><br><span class="line">                compress: &#123;</span><br><span class="line">                    /*</span><br><span class="line">                     是否在UglifyJS删除没有用到的代码时输出警告信息，默认为输出，可以设置为false关闭这些作用</span><br><span class="line">                     不大的警告</span><br><span class="line">                    */</span><br><span class="line">                    warnings: false,</span><br><span class="line"></span><br><span class="line">                    /*</span><br><span class="line">                     是否删除代码中所有的console语句，默认为不删除，开启后，会删除所有的console语句</span><br><span class="line">                    */</span><br><span class="line">                    drop_console: true,</span><br><span class="line"></span><br><span class="line">                    /*</span><br><span class="line">                     是否内嵌虽然已经定义了，但是只用到一次的变量，比如将 var x = 1; y = x, 转换成 y = 5, 默认为不</span><br><span class="line">                     转换，为了达到更好的压缩效果，可以设置为false</span><br><span class="line">                    */</span><br><span class="line">                    collapse_vars: true,</span><br><span class="line"></span><br><span class="line">                    /*</span><br><span class="line">                     是否提取出现了多次但是没有定义成变量去引用的静态值，比如将 x = &apos;xxx&apos;; y = &apos;xxx&apos;  转换成</span><br><span class="line">                     var a = &apos;xxxx&apos;; x = a; y = a; 默认为不转换，为了达到更好的压缩效果，可以设置为false</span><br><span class="line">                    */</span><br><span class="line">                    reduce_vars: true</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;),</span><br><span class="line">        //将js自动插入到html里</span><br><span class="line">        new HtmlWebpackPlugin(&#123;</span><br><span class="line">            template: &apos;./views/index.html&apos;,</span><br><span class="line">            filename: &apos;index.html&apos;,</span><br><span class="line">        &#125;),</span><br><span class="line">        new webpack.HotModuleReplacementPlugin() //引入热更新插件</span><br><span class="line">    ]</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h3 id="优化"><a href="#优化" class="headerlink" title="优化"></a>优化</h3><p>优化主要是针对打包速度跟打包大小优化，主要包含以下方面</p>
<ol>
<li>对于 Webpack4，打包项目使用 production 模式，这样会自动开启代码压缩</li>
<li>使用 ES6 模块来开启 tree shaking，这个技术可以移除没有使用的代码</li>
<li>优化图片，对于小图可以使用 base64 的方式写入文件中</li>
<li>按照路由拆分代码，实现按需加载</li>
<li>给打包出来的文件名添加哈希，实现浏览器缓存文件(主要采用chunkFilename)</li>
</ol>
<h4 id="打包速度"><a href="#打包速度" class="headerlink" title="打包速度"></a>打包速度</h4><ol>
<li>减少文件搜索范围，比如通过另名，loader的test,include &amp; exclude</li>
<li>resolve.module，配置webpack去哪些目录下妙手第三方模块</li>
<li>resolve.aslias配置，通过另外来将原导入路径映射成一个新的导入路径</li>
<li>Webpack4默认压缩并行</li>
<li><p>Happypack并发调用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">threads:开启几个子进程去处理这一类型的文件，默认是3个，必须整数</span><br><span class="line">verbose:是否允许happypack输出日志，默认是true</span><br><span class="line">threadpool:代表共享进程池，即多个happypack实例都使用同一个共享进程池中的子进程去处理任务，以防止资源占用过多</span><br></pre></td></tr></table></figure>
</li>
<li><p>Babel使用缓存编译，主要loader参数后面增加cacheDirectory，关于<a href="https://mp.weixin.qq.com/s/NRZQI-Md0dqNAGY96qsn-A" target="_blank" rel="noopener">babel编译原理</a></p>
</li>
<li>使用DllPlugin和DllReferencePlugin，这两个跟CommonsChunkPlugin（webpack3中的，webpack4中使用SplitChunksPlugin）有一些区别，主要区别如下</li>
</ol>
<ul>
<li>CommonsChunkPlugin 插件每次打包的时候还是会去处理一些第三方依赖库，只是它能把第三方库文件和我们的代码分开掉，生成一个独立的js文件，但它不能提高打包速度。</li>
<li>DLLPlugin 它能把第三方库代码分离开，并且每次文件更改的时候，它只会==打包该项目自身==的代码。所以打包速度会更快。</li>
</ul>
<p>介绍DllPlugin插件跟DllReferencePlugin插件</p>
<p>DllPlugin插件 : 用于打包出一个个单独的动态链接库文件 。<br>DllReferencePlugin 插件:用于在主要的配置文件中引入 DllP!ugin 插件打包好的动态链接库文件。</p>
<p>具体配置如下：</p>
<p>webpack.dll.config.js配置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">const path = require(&apos;path&apos;);</span><br><span class="line">const DllPlugin = require(&apos;webpack/lib/DllPlugin&apos;);</span><br><span class="line"></span><br><span class="line">module.exports = &#123;</span><br><span class="line">    // 入口文件</span><br><span class="line">    entry: &#123;</span><br><span class="line">        // 项目中用到该两个依赖库文件</span><br><span class="line">        jquery: [&apos;./libs/jquery&apos;],</span><br><span class="line">        // echarts: [&apos;echarts&apos;]</span><br><span class="line">    &#125;,</span><br><span class="line">    // 输出文件</span><br><span class="line">    output: &#123;</span><br><span class="line">        // 文件名称</span><br><span class="line">        filename: &apos;[name].dll.js&apos;,</span><br><span class="line">        // 将输出的文件放到dist目录下</span><br><span class="line">        path: path.resolve(__dirname, &apos;dill&apos;),</span><br><span class="line">        /*</span><br><span class="line">         存放相关的dll文件的全局变量名称，比如对于jquery来说的话就是 _dll_jquery, 在前面加 _dll</span><br><span class="line">         是为了防止全局变量冲突。</span><br><span class="line">        */</span><br><span class="line">        library: &apos;_dll_[name]&apos;</span><br><span class="line">    &#125;,</span><br><span class="line">    plugins:[</span><br><span class="line">        // 使用插件 DllPlugin</span><br><span class="line">    new DllPlugin(&#123;</span><br><span class="line">        /*</span><br><span class="line">         该插件的name属性值需要和 output.library保存一致，该字段值，也就是输出的 manifest.json文件中name字段的值。</span><br><span class="line">         比如在jquery.manifest文件中有 name: &apos;_dll_jquery&apos;</span><br><span class="line">        */</span><br><span class="line">        name: &apos;_dll_[name]&apos;,</span><br><span class="line">  </span><br><span class="line">        /* 生成manifest文件输出的位置和文件名称 */</span><br><span class="line">        path: path.join(__dirname, &apos;dill&apos;, &apos;[name].manifest.json&apos;)</span><br><span class="line">      &#125;)</span><br><span class="line">    ]</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>webpack.config.js配置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">const DllReferencePlugin = require(&apos;webpack/lib/DllReferencePlugin&apos;);</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">    plugins:</span><br><span class="line">    [</span><br><span class="line">        // 告诉webpack使用了哪些第三方库代码</span><br><span class="line">		new DllReferencePlugin(&#123;</span><br><span class="line">			// jquery 映射到json文件上去</span><br><span class="line">			manifest: require(&apos;./dill/jquery.manifest.json&apos;)</span><br><span class="line">		&#125;)</span><br><span class="line">	]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h3><h4 id="1-webpack运行流程"><a href="#1-webpack运行流程" class="headerlink" title="1.webpack运行流程"></a>1.webpack运行流程</h4><p>1.1 webpack事件流</p>
<p>Webpack 就像一条生产线，要经过一系列处理流程后才能将源文件转换成输出结果。 这条生产线上的每个处理流程的职责都是单一的，多个流程之间有存在依赖关系，只有完成当前处理后才能交给下一个流程去处理。 插件就像是一个插入到生产线中的一个功能，在特定的时机对生产线上的资源做处理。 Webpack 通过 <a href="https://juejin.im/post/5abf33f16fb9a028e46ec352" target="_blank" rel="noopener">Tapable</a> 来组织这条复杂的生产线。 Webpack 在运行过程中会广播事件，插件只需要监听它所关心的事件，就能加入到这条生产线中，去改变生产线的运作。 Webpack 的事件流机制保证了插件的有序性，使得整个系统扩展性很好。</p>
<p>1.2 webpack运行流程详解</p>
<p>Webpack 的运行流程是一个串行的过程，从启动到结束会依次执行以下流程。</p>
<ul>
<li>初始化参数：从配置文件和Shell语句中读取与合并参数，得出最终的参数。</li>
<li>开始编译：用上一步得到的参数初始化Compiler对象，加载所有配置的插件，通过执行对象的run方法开始执行编译。</li>
<li>确定入口：根据配置中的entry找出所有入口文件。</li>
<li>编译模块：从入口文件出发，调用所有配置的loader对模块进行翻译，再找出该模块依赖的模块，再递归本步骤走到所有入口依赖的文件都经过了本步骤的处理。</li>
<li>完成模块编译：在经过第4步使用loader翻译完所有模块后，得到了每个模块被翻译后的最终内容及它们之间的依赖关系。</li>
<li>输出资源：根据入口和模块之间的依赖关系，组装成一个个包含多个模块的Chunk，再将每个Chunk转换成一个单独的文件加入输出列表中，这是可以修改输出内容的最后机会。</li>
<li>输出完成：在确定好输出内容后，根据配置确定输出的路径和文件名，将文件的内容写入文件系统中。</li>
</ul>
<p>流程图：</p>
<p><img src="/images/webpack/01.jpg" alt="image"></p>
<p>2.3 抽象语法树（AST）</p>
<blockquote>
<p>在计算机科学中，抽象语法树（Abstract Syntax Tree，AST），或简称语法树（Syntax tree），是源代码语法结构的一种抽象表示。它以树状的形式表现编程语言的语法结构，树上的每个节点都表示源代码中的一种结构。之所以说语法是“抽象”的，是因为这里的语法并不会表示出真实语法中出现的每个细节。比如，嵌套括号被隐含在树的结构中，并没有以节点的形式呈现；而类似于 if-condition-then 这样的条件跳转语句，可以使用带有两个分支的节点来表示。</p>
</blockquote>
<p>实际上一段代码经过编译器的词分析、语法分析等阶段之后，会生成一个树状结构的“抽象语法树（AST）”，该语法树的每一个节点都对应着代码当中不同含义片段。</p>
<p>解释器是将AST翻译成目标语言并运行的工具。</p>
<h3 id="手写webpack插件"><a href="#手写webpack插件" class="headerlink" title="手写webpack插件"></a>手写webpack插件</h3><ul>
<li>调用插件apply函数传入compiler对象</li>
<li>通过compiler对象监听</li>
</ul>
<p>插件代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">//@file: plugins/myplugin.js</span><br><span class="line">class myPlugin &#123;</span><br><span class="line">    constructor(options)&#123;</span><br><span class="line">        //用户自定义配置</span><br><span class="line">        this.options = options</span><br><span class="line">        console.log(this.options)</span><br><span class="line">    &#125;</span><br><span class="line">    apply(compiler) &#123;</span><br><span class="line">        console.log(&quot;This is my first plugin.&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">module.exports = myPlugin</span><br></pre></td></tr></table></figure>
<p>webpack代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">const MyPlugin = require(&apos;./plugins/myplugin-4.js&apos;)</span><br><span class="line"></span><br><span class="line">module.exports = &#123;</span><br><span class="line">    ......,</span><br><span class="line">    plugins: [</span><br><span class="line">        new MyPlugin(&quot;Plugin is instancing.&quot;)</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>具体参数可以参考《深入浅出webpack》</p>
<h3 id="手写loader"><a href="#手写loader" class="headerlink" title="手写loader"></a>手写loader</h3><ol>
<li>获得loader的options，是通过<code>require (’ loader-utils ’);</code></li>
<li>返回其他结果，是调用<code>callback</code></li>
<li>缓存加速，调用this.cacheable(false);</li>
</ol>
<p>具体参数可以参考《深入浅出webpack》</p>
<h4 id="loader文件"><a href="#loader文件" class="headerlink" title="loader文件"></a>loader文件</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">const loaderUtils = require(&apos;loader-utils&apos;);</span><br><span class="line"></span><br><span class="line">module.exports = function (content) &#123;</span><br><span class="line">    // 获取用户配置的options 同步</span><br><span class="line">    const options=loaderUtils.getOptions(this);</span><br><span class="line">    console.log(&apos;***options***&apos;,options);</span><br><span class="line">    this.callback(null,&apos;&#123;&#125;&apos;+content);</span><br><span class="line">    return &apos;&#123;&#125;;&apos;+content;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="webpack配置文件"><a href="#webpack配置文件" class="headerlink" title="webpack配置文件"></a>webpack配置文件</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    test: /\.js$/,</span><br><span class="line">    exclude: /node_modules/,</span><br><span class="line">       use: &#123;</span><br><span class="line">           //这里是我的自定义loader的存放路径</span><br><span class="line">           loader: path.resolve(&apos;./loaders/index.js&apos;),</span><br><span class="line">           options: &#123;</span><br><span class="line">              test: 1</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>webpack打包配置相对比较复杂，目前介绍应该可以满常规需求。</p>
<p>参考资料：</p>
<p>《深入浅出webpack》</p>
<p><a href="https://github.com/jerryOnlyZRJ/webpack-loader/blob/master/docs/webpack-principle.md" target="_blank" rel="noopener">Webpack运行机制</a></p>
<p><a href="https://github.com/jerryOnlyZRJ/webpack-loader/blob/master/docs/webpack-plugin.md" target="_blank" rel="noopener">编写自定义webpack plugin</a></p>
<p><a href="https://github.com/jerryOnlyZRJ/webpack-loader/blob/master/docs/webpack-loader.md" target="_blank" rel="noopener">编写自定义webpack loader</a></p>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center">
  <div>Donate comment here</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Tony 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Tony 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/12/08/比较运算符面试题/" rel="next" title="比较运算符面试题">
                <i class="fa fa-chevron-left"></i> 比较运算符面试题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/12/10/BFC原理/" rel="prev" title="BFC原理">
                BFC原理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">65</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#内容"><span class="nav-number">1.</span> <span class="nav-text">内容</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#介绍、安装及常用命令"><span class="nav-number">2.</span> <span class="nav-text">介绍、安装及常用命令</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#什么是webpack"><span class="nav-number">2.1.</span> <span class="nav-text">什么是webpack</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#webpack特点"><span class="nav-number">2.2.</span> <span class="nav-text">webpack特点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#webpack安装"><span class="nav-number">2.3.</span> <span class="nav-text">webpack安装</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#常用命令"><span class="nav-number">2.4.</span> <span class="nav-text">常用命令</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#最简单配置"><span class="nav-number">3.</span> <span class="nav-text">最简单配置</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#webpack相关参数介绍"><span class="nav-number">3.1.</span> <span class="nav-text">webpack相关参数介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-entry"><span class="nav-number">3.1.1.</span> <span class="nav-text">1. entry</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-output"><span class="nav-number">3.1.2.</span> <span class="nav-text">2. output</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-module"><span class="nav-number">3.1.3.</span> <span class="nav-text">3. module</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-resolve"><span class="nav-number">3.1.4.</span> <span class="nav-text">4. resolve</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#webpack配置"><span class="nav-number">4.</span> <span class="nav-text">webpack配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优化"><span class="nav-number">5.</span> <span class="nav-text">优化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#打包速度"><span class="nav-number">5.1.</span> <span class="nav-text">打包速度</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#原理"><span class="nav-number">6.</span> <span class="nav-text">原理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-webpack运行流程"><span class="nav-number">6.1.</span> <span class="nav-text">1.webpack运行流程</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#手写webpack插件"><span class="nav-number">7.</span> <span class="nav-text">手写webpack插件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#手写loader"><span class="nav-number">8.</span> <span class="nav-text">手写loader</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#loader文件"><span class="nav-number">8.1.</span> <span class="nav-text">loader文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#webpack配置文件"><span class="nav-number">8.2.</span> <span class="nav-text">webpack配置文件</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">9.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>